from tparser.model import DeclarativeBase
from sqlalchemy import Column, ForeignKey, Index, Integer, String, DateTime, Date, Time, Float, Enum, Boolean
from sqlalchemy.sql import func
from sqlalchemy.orm import relation, backref


class TripPlan(DeclarativeBase):
    '''TripPlan is the master record showing the start and end points

       TripPlan has a 1:N relationship with Itinerary, where different Itineraries can represent differnt
       modes, trip planners, dates and times...
    '''
    __tablename__ = 'trip_plan'
    id = Column(Integer, primary_key=True)

    origin_name = Column(String)
    origin_lat = Column(Float)
    origin_lon = Column(Float)

    destination_name = Column(String)
    destination_lat = Column(Float)
    destination_lon = Column(Float)
    created = Column(DateTime, default=func.current_timestamp())


class Itinerary(DeclarativeBase):
    '''Itinerary holds many of the parameters that define a given transit trip itinerary

    '''
    __tablename__ = 'itinerary'
    id = Column(Integer, primary_key=True)
    app_name = Column(String)
    success = Column(Boolean)
    message = Column(String)
    ws_url = Column(String)
    app_url = Column(String)

    mode = Column(String)
    date = Column(Date)
    start_time = Column(Time)
    end_time = Column(Time)

    wait_time = Column(Integer)
    walk_time = Column(Integer)
    transit_time = Column(Integer)
    durration = Column(Integer)
    transfers = Column(Integer)
    distance = Column(Float)

    created = Column(DateTime, default=func.current_timestamp())
    trip_id = Column(
        Integer,
        ForeignKey(TripPlan.id),
        nullable=False
    )
    trip = relation(TripPlan, backref=backref('itineraries', order_by=id))

    def find_transit_legs(self, not_ids):
        '''
            TODO: describe what I do ... fix logic
        '''
        retVal = {};
        for p in self.transit_legs:
            if p.name in not_ids:
                continue;
            retVal[p.name] = p.value;

        return retVal;


class TransitLeg(DeclarativeBase):
    '''Transit Leg describes the route and origin and destination points of a ride on transit vehicle 

    '''
    __tablename__ = 'transit_leg'
    id = Column(Integer, primary_key=True)

    route_name = Column(String)
    route_id = Column(String)
    stay_on_board = Column(Boolean, default=False)

    origin_name = Column(String)
    origin_id = Column(String)
    origin_lat = Column(Float)
    origin_lon = Column(Float)

    destination_name = Column(String)
    destination_id = Column(String)
    destination_lat = Column(Float)
    destination_lon = Column(Float)
    itinerary_id = Column(
        Integer,
        ForeignKey(Itinerary.id),
        nullable=False
    )
    itinerary = relation(Itinerary, backref=backref('transit_legs', order_by=id))
